<?php

namespace addons\alispeech\controller;

use AlibabaCloud\Client\AlibabaCloud;
use app\admin\model\Admin;
use app\common\library\Upload;
use app\common\model\Attachment;
use think\addons\Controller;
use addons\bdtts\library\AipSpeech;
use think\Cache;

class Index extends Controller
{

    private $config;

    public function index()
    {

        if(!$config=Cache::get('cdk')) {
            $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
            if ($data_auth['code'] == 0) {
                $this->error($data_auth['msg']);
            }

            $config = $data_auth['data'];
            Cache::set('cdk',$config,86400);
        }

        if (empty($config['accessKeyId']) || empty($config['accessKeySecret'])) {
            $this->error('请先配置必要的参数');
        }
        $post = $this->request->post();
        if (!(isset($post['text']) && !empty($post['text']))) {
            $this->error('必填参数为空');
        }


        if(!$token=Cache::get('alispeech'))
        {
            AlibabaCloud::accessKeyClient(
                $config['accessKeyId'],
                $config['accessKeySecret'])
                ->regionId("cn-shanghai")
                ->asDefaultClient();
            try {
                $response = AlibabaCloud::nlsCloudMeta()
                    ->v20180518()
                    ->createToken()
                    ->request();

                $token = $response["Token"];
                if ($token != NULL) {
                    $token=$response["Token"]['Id'];
                    Cache::set('alispeech',$token,3600*5);
                }

                else {
                    $this->error("token 获取失败");
                }
            } catch (ClientException $exception) {
                // 获取错误消息
                $this->error($exception->getErrorMessage());
            } catch (ServerException $exception) {
                // 获取错误消息
                $this->error($exception->getErrorMessage());
            }

        }

        $temp_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'alispeech';
        if (!is_dir($temp_path)) {
            $dirres = mkdir($temp_path, 0700);
            if (!$dirres) {
                $this->error('无法自动创建缓存目录！请手动创建:' . $temp_path);
            }
        }


        $rnd = substr(time(), -4);
        $file_name = date('Ymd') . $rnd . rand(0, 9) . rand(0, 9) . rand(0, 9) . '.wav';
        $filename = cdnurl( '/uploads/alispeech/' . $file_name);
        $file_name = $temp_path . DS . $file_name;





       $this->config=[
           'appkey'=>'yZ0RAPHXyNOhRH5x',
           'text'=>$post['text'],
           'token'=>$token,
           'format'=>'wav',
           'sample_rate'=>16000,
           'voice'=>'xiaoyun',


       ];
        if(isset($post['volume'])) $this->config['volume']=$post['volume'];
        if(isset($post['voice'])) $this->config['voice']=$post['voice'];
        if( isset($post['speech_rate'])) $this->config['speech_rate']=$post['speech_rate'];
        if( isset($post['pitch_rate'])) $this->config['pitch_rate']=$post['pitch_rate'];


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 只支持post
        curl_setopt($ch, CURLOPT_POST, 1);

        // 请求体
        $json = json_encode($this->config, JSON_UNESCAPED_UNICODE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 设置请求头
        $header = [
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($json)
        ];
        /*if($this->config['X-NLS-Token']){
            $header['X-NLS-Token'] = $this->config['X-NLS-Token'];
        }*/
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $output = curl_exec($ch);
        $curlError = curl_close($ch);

        // curl执行失败
        if($output === false) {
            return json(['code'=>0,'msg'=>$curlError,'data'=>['audio_name'=>'']]);
        }
        $res = json_decode($output, true);
        if($res){
              return json(['code'=>0,'msg'=>$res['status'].'_'.$res['message'],'data'=>['audio_name'=>'']]);
        }else{
            $writeRes = file_put_contents($file_name, $output);
            // 写入失败
            if($writeRes === false){
                return json( ['code'=>0,'msg'=>'合成失败','data'=>['audio_name'=>'']]);
            }
            return json(['code' => 1, 'msg' => '合成成功', 'data' => ['audio_name' => $filename]]);
        }


    }



    public function upload()
    {



        $post = $this->request->post();
        if (!(isset($post['str']) && !empty($post['str']))) {
            $this->error('文本参数为空');
        }
        if (!(isset($post['url']) && !empty($post['url']))) {
            $this->error('url参数为空');
        }
        $basename = pathinfo(parse_url($post['url'])['path'])['basename'];

        $file=$temp_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'alispeech/'.$basename;
        $path = str_ireplace('\\', '/', str_ireplace(ROOT_PATH . 'public', '', $file));

        $res = Upload::VodClient($file,'wav', mb_substr($post['str'], 0, 90));
        $params = array(
            'admin_id'    => (int)session('admin.id'),
            'user_id'     => (int)cookie('uid'),
            'filename'    => str_ireplace(array('/', '\\', '|', '?', '*', ':', '"', '<', '>'), '_', mb_substr($post['str'], 0, 90)),
            'filesize'    => 1024,
            'imagewidth'  => 0,
            'imageheight' => 0,
            'imagetype'   => 'wav',
            'imageframes' => 0,
            'mimetype'    => 'wav/wav',
            'url'         => $path,
            'uploadtime'  => time(),
            'storage'     => 'vod',
            'sha1'        => '',
            'type'        => 2,
            'extparam'    => '',
            'file_id'     => $res->FileId,
            'vod_url'     => $res->MediaUrl,
        );
        $attachment = new Attachment();
        $attachment->data(array_filter($params));
        $attachment->save();
        if (!empty($attachment->file_id)) {
            $attachment->url = $attachment->url . (stripos($attachment->url, '?') === false ? '?' : '&') . 'vod_id=' . $attachment->id;
            $attachment->save();
        }
         $this->success('成功加入语音库');


    }







}
